'use client'

import { useState } from 'react'
import { motion } from 'framer-motion'
import { Eye, EyeOff, UserPlus, ArrowLeft, School, GraduationCap } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { register } from '@/lib/auth-client'

export default function RegisterPage() {
  const router = useRouter()
  const [showPassword, setShowPassword] = useState(false)
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    confirmPassword: '',
    school: '',
    gradeLevel: ''
  })
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const gradeOptions = [
    { value: '1', label: '小学1年级' },
    { value: '2', label: '小学2年级' },
    { value: '3', label: '小学3年级' },
    { value: '4', label: '小学4年级' },
    { value: '5', label: '小学5年级' },
    { value: '6', label: '初中1年级' },
    { value: '7', label: '初中2年级' },
    { value: '8', label: '初中3年级' },
    { value: '9', label: '初中4年级' },
  ]

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')
    setSuccess('')

    // 表单验证
    if (!formData.username) {
      setError('请输入用户名')
      setIsLoading(false)
      return
    }

    if (formData.username.length < 3) {
      setError('用户名至少3个字符')
      setIsLoading(false)
      return
    }

    if (!/^[A-Za-z0-9_]+$/.test(formData.username)) {
      setError('用户名只能包含字母、数字和下划线')
      setIsLoading(false)
      return
    }

    if (formData.password.length < 6) {
      setError('密码长度不能少于6位')
      setIsLoading(false)
      return
    }

    if (formData.password !== formData.confirmPassword) {
      setError('两次输入的密码不一致')
      setIsLoading(false)
      return
    }

    if (!formData.gradeLevel) {
      setError('请选择年级')
      setIsLoading(false)
      return
    }

    try {
      // 调用注册API
      const response = await register({
        username: formData.username,
        password: formData.password,
        school: formData.school || undefined,
        gradeLevel: parseInt(formData.gradeLevel),
      })

      if (response.success) {
        setSuccess('注册成功！正在跳转到仪表板...')
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          router.push('/dashboard')
        }, 1500)
      } else {
        setError(response.error || '注册失败，请稍后重试')
      }
    } catch (err) {
      console.error('注册错误:', err)
      setError('注册失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900" />
      
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="relative w-full max-w-md"
      >
        {/* 返回首页按钮 */}
        <Link href="/">
          <Button
            variant="glassmorphism"
            size="sm"
            className="mb-6 glassmorphism-button"
          >
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回首页
          </Button>
        </Link>

        <Card glassmorphism className="backdrop-blur-xl">
          <CardHeader className="text-center">
            <motion.div
              initial={{ scale: 0.8 }}
              animate={{ scale: 1 }}
              transition={{ duration: 0.5, delay: 0.1 }}
            >
              <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gradient-to-r from-green-500 to-blue-600 flex items-center justify-center">
                <UserPlus className="w-8 h-8 text-white" />
              </div>
            </motion.div>
            <CardTitle className="text-2xl font-bold text-gray-800 dark:text-gray-200">
              加入奥数学院
            </CardTitle>
            <CardDescription className="text-gray-600 dark:text-gray-300">
              创建您的学习账户，开始奥数之旅
            </CardDescription>
          </CardHeader>

          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-6">
              {error && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="p-3 rounded-lg bg-red-100 border border-red-300 text-red-700 text-sm"
                >
                  {error}
                </motion.div>
              )}

              {success && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="p-3 rounded-lg bg-green-100 border border-green-300 text-green-700 text-sm"
                >
                  {success}
                </motion.div>
              )}

              <div className="space-y-4">

                <div>
                  <label htmlFor="username" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    用户名
                  </label>
                  <Input
                    id="username"
                    name="username"
                    type="text"
                    required
                    glassmorphism
                    placeholder="请输入用户名（字母或字母+数字，且以字母开头）"
                    value={formData.username}
                    onChange={handleInputChange}
                    className="transition-all duration-300 focus:scale-105"
                  />
                </div>

                <div>
                  <label htmlFor="school" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    <School className="w-4 h-4 inline mr-1" />
                    所在学校
                  </label>
                  <Input
                    id="school"
                    name="school"
                    type="text"
                    required
                    glassmorphism
                    placeholder="请输入学校名称"
                    value={formData.school}
                    onChange={handleInputChange}
                    className="transition-all duration-300 focus:scale-105"
                  />
                </div>

                <div>
                  <label htmlFor="gradeLevel" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    <GraduationCap className="w-4 h-4 inline mr-1" />
                    年级
                  </label>
                  <select
                    id="gradeLevel"
                    name="gradeLevel"
                    required
                    value={formData.gradeLevel}
                    onChange={handleInputChange}
                    className="flex h-10 w-full rounded-md border border-input glassmorphism border-white/30 bg-white/20 px-3 py-2 text-sm ring-offset-background placeholder:text-gray-400 text-gray-800 dark:text-gray-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-300 focus:scale-105"
                  >
                    <option value="">请选择年级</option>
                    {gradeOptions.map((option) => (
                      <option key={option.value} value={option.value} className="bg-white dark:bg-gray-800">
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    密码 <span className="text-xs text-gray-500">(至少6位)</span>
                  </label>
                  <div className="relative">
                    <Input
                      id="password"
                      name="password"
                      type={showPassword ? 'text' : 'password'}
                      required
                      glassmorphism
                      placeholder="请输入密码"
                      value={formData.password}
                      onChange={handleInputChange}
                      className="pr-10 transition-all duration-300 focus:scale-105"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                    >
                      {showPassword ? (
                        <EyeOff className="w-4 h-4" />
                      ) : (
                        <Eye className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                </div>

                <div>
                  <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    确认密码
                  </label>
                  <Input
                    id="confirmPassword"
                    name="confirmPassword"
                    type="password"
                    required
                    glassmorphism
                    placeholder="请再次输入密码"
                    value={formData.confirmPassword}
                    onChange={handleInputChange}
                    className="transition-all duration-300 focus:scale-105"
                  />
                </div>
              </div>

              <Button
                type="submit"
                variant="gradient"
                className="w-full py-3 text-lg font-semibold transition-all duration-300 hover:scale-105"
                disabled={isLoading}
              >
                {isLoading ? (
                  <motion.div
                    animate={{ rotate: 360 }}
                    transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                    className="w-5 h-5 border-2 border-white border-t-transparent rounded-full"
                  />
                ) : (
                  <>
                    <UserPlus className="w-5 h-5 mr-2" />
                    注册账户
                  </>
                )}
              </Button>
            </form>

            <div className="mt-6 text-center">
              <p className="text-sm text-gray-600 dark:text-gray-300">
                已有账户？{' '}
                <Link
                  href="/auth/login"
                  className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
                >
                  立即登录
                </Link>
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 装饰性元素 */}
        <div className="absolute -top-10 -left-10 w-20 h-20 bg-gradient-to-r from-green-400 to-blue-500 rounded-full opacity-20 animate-float" />
        <div className="absolute -bottom-10 -right-10 w-16 h-16 bg-gradient-to-r from-blue-400 to-purple-500 rounded-full opacity-20 animate-float" style={{ animationDelay: '2s' }} />
      </motion.div>
    </div>
  )
}
